package com.whale.nangua.pumpkingobang.aty;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
import android.widget.VideoView;
import android.content.pm.ActivityInfo;
import com.example.wuziqi.R;

public class SplashActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);  // 设置布局

        // 强制横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        // 找到 VideoView 控件
        VideoView videoView = findViewById(R.id.videoView);

        // 设置视频路径
        Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.load);
        videoView.setVideoURI(videoUri);

        // 当视频准备好时调整 VideoView 尺寸
        videoView.setOnPreparedListener(mp -> {
            // 获取视频的宽高
            int videoWidth = mp.getVideoWidth();
            int videoHeight = mp.getVideoHeight();
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            int screenHeight = getResources().getDisplayMetrics().heightPixels;

            // 计算视频的宽高比
            float videoRatio = (float) videoWidth / videoHeight;
            float screenRatio = (float) screenWidth / screenHeight;

            // 如果视频的宽高比大于屏幕的宽高比，按宽度适配
            if (videoRatio < screenRatio) {
                // 按宽度适配
                videoView.setLayoutParams(new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth / videoRatio)));
            } else if (videoRatio > screenRatio) {
                // 如果视频的宽高比小于屏幕的宽高比，按高度适配
                videoView.setLayoutParams(new RelativeLayout.LayoutParams((int) (screenHeight * videoRatio), screenHeight));
            } else {
                // 如果视频的宽高比等于屏幕的宽高比，直接填充屏幕
                videoView.setLayoutParams(new RelativeLayout.LayoutParams(screenWidth, screenHeight));
            }

            // 开始播放视频
            videoView.start();
        });

        // 设置触摸事件监听，点击屏幕跳过视频
        videoView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // 如果点击了屏幕，跳过视频并跳转到 InitAty
                Intent intent = new Intent(SplashActivity.this, InitAty.class);
                startActivity(intent);
                finish();  // 结束 SplashActivity，防止返回到启动画面
                return true;  // 返回 true，表示事件已处理
            }
            return false;  // 返回 false，让事件继续传递
        });

        // 视频播放完成后跳转
        videoView.setOnCompletionListener(mp -> {
            new Handler().postDelayed(() -> {
                Intent intent = new Intent(SplashActivity.this, InitAty.class);  // 跳转到 InitAty
                startActivity(intent);
                finish();
            }, 1000);  // 延时 3 秒
        });
    }
}
